<template>
	<div class="editor-container">
		<el-card shadow="hover" class="h100 mb10">
			<center>
				<el-button-group class="mr10" size="small">
					<el-button :disabled="terminalContent.viewed" @click="editorClear">清空</el-button>
					<el-button v-if="terminalContent.viewed" @click="editorEdit">编辑</el-button>
					<el-button v-else @click="editorView">预览</el-button>
					<el-button :disabled="terminalContent.viewed" @click="editorSave">保存</el-button>
				</el-button-group>
			</center>
		</el-card>
		<el-row :gutter="10">
			<el-col :xs="24" :sm="24" :md="5" :lg="5" :xl="5" class="mb20">
				<el-card shadow="hover" class="h100">
					<LeftBarPanel ref="leftBarPanel"></LeftBarPanel>
				</el-card>
			</el-col>
			<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" class="mb20">
				<el-scrollbar ref="scrollbarRef" class="main-content-warp h100" :class="`${terminalContent.viewed ? '' : 'main-content-gird'}`">
					<div class="main-editor" :style="{width: `${terminalContent.width}px`}" @click.stop>
						<EditorPanel ref="editorPanelRef"></EditorPanel>
					</div>
				</el-scrollbar>
			</el-col>
			<el-col :xs="24" :sm="24" :md="7" :lg="7" :xl="7" class="mb20" @click.stop>
				<el-card shadow="hover" class="h100">
					<el-tabs v-model="activeTabName">
						<el-tab-pane label="画布图层" name="LayerPanel">
							<LayerPanel v-if="componentsData.length > 0" @scroll="scrollToTop" @config="switchToToolBar"></LayerPanel>
							<el-empty v-else description="请从左侧拖拽添加一个组件"/>
						</el-tab-pane>
						<el-tab-pane label="组件设置" name="ToolBarPanel">
							<ToolBarPanel></ToolBarPanel>
						</el-tab-pane>
						<el-tab-pane label="画布设置" name="TerminalPanel">
							<TerminalPanel></TerminalPanel>
						</el-tab-pane>
					</el-tabs>
				</el-card>
			</el-col>
		</el-row>
	</div>
</template>

<script lang="ts">
	import { ref, toRefs, reactive, onMounted, computed, } from 'vue';
	import { ElMessage } from 'element-plus';
	import { useStore } from '/@/store/index';
	import { Local, Session } from '/@/utils/storage';
	import { useRoute } from 'vue-router';
	import axios from 'axios';
	
	import { getWebPoster } from '/@/api/dragdesign/poster/index';
	import { getWebTerminal, addWebTerminal, editWebTerminal } from '/@/api/dragdesign/terminal/index';
	
	import LeftBarPanel from '/@/views/decorator/components/leftBar/index.vue';
	import ToolBarPanel from '/@/views/decorator/components/toolBar/index.vue';
	import EditorPanel from '/@/views/decorator/components/index.vue';
	import TerminalPanel from '/@/views/decorator/components/terminal.vue';
	import LayerPanel from '/@/views/decorator/components/layer.vue';
	
	export default {
		name: 'decorator',
		components: {
			LeftBarPanel,
			ToolBarPanel,
			EditorPanel,
			TerminalPanel,
			LayerPanel,
		},
		setup() {
			const editorPanelRef = ref();
			const scrollbarRef = ref();
			const store = useStore();
			const route = useRoute();
			const state = reactive({
				editorId: '',
				posterId: '',
				terminal: 1,
				terminalContent: {},
				activeComponent: {},
				componentsData: [],
				activeTabName: 'ToolBarPanel',
			});

			state.terminal = computed(() => store.state.decorator.terminal);
			state.terminalContent = computed(() => store.state.decorator.terminalContent);
			state.activeComponent = computed(() => store.state.decorator.activeComponent);
			state.componentsData = computed(() => store.state.decorator.componentsData);
			state.componentsFormData = computed(() => store.state.decorator.componentsFormData);
			
			const setTerminal = (terminal) => {
				store.dispatch('decorator/setTerminal', terminal);
			};
			const setTerminalContent = (terminalContent) => {
				store.dispatch('decorator/setTerminalContent', terminalContent);
			};
			const setActiveComponent = (activeComponent) => {
				store.dispatch('decorator/setActiveComponent', activeComponent);
			};
			const setComponentsData = (componentsData) => {
				store.dispatch('decorator/setComponentsData', componentsData);
			};

			const toggleDevice = (terminal) => {
				setTerminal(terminal);
				setActiveComponent({});
			}

			// 保存画布
			const editorSave = () => {
				// Local.set('terminal', state.terminal);
				// Local.set('terminalContent', state.terminalContent);
				// Local.set('componentsData', state.componentsData);
				// ElMessage.success('保存成功');
				
				const params = {
					id: state.editorId,
					posterId: state.posterId,
					terminal: state.terminal,
					terminalContent: JSON.stringify(state.terminalContent),
					terminalComponent: JSON.stringify(state.componentsData),
				}
				//使用原生axios处理避免Loading弹窗影响等待操作体验
				axios.post(state.editorId ? editWebTerminal() : addWebTerminal(), params, {
					headers: {
						'Authorization': `Bearer ${Session.get('token')}`,
						'Content-Type': 'application/json',
					}
				}).then(res => {
					if(res.status == 200){
						if(res.data.code == 0 && res.data.data){
							ElMessage.success('保存成功');
							state.editorId = res.data.data.id;
						}
					}
				}).catch(error => {
					const res = error.response;
					ElMessage.error(res.data.msg || res.statusText);
				});
			}
			// 预览画布
			const editorView = () => {
				state.terminalContent.viewed = true;
			}
			// 编辑画布
			const editorEdit = () => {
				state.terminalContent.viewed = false;
			}
			// 清空画布
			const editorClear = () => {
				setComponentsData([]);
			}
			// 删除组件
			const delComponent = (id) => {
				const data = state.componentsData.filter(item => item.id == id)[0];
				const index = state.componentsData.indexOf(data);
				if(index > -1){
					state.componentsData.splice(index, 1);
				}
				setActiveComponent({});
			}
			// 滚动组件
			const scrollToTop = () => {
				const activeDom = document.getElementById(state.activeComponent.id);
				if(activeDom && activeDom.parentNode){
					scrollbarRef.value!.setScrollTop(activeDom.parentNode.offsetTop - 100);
				}
			}
			const switchToToolBar = () => {
				state.activeTabName = 'ToolBarPanel';
			}
			
			// 装载数据
			const loadWebTerminal = async (params) => {
				let terminal = 1;
				let terminalContent = {
					width: 415,
					title: '',//网页标题
					viewed: false,//只读状态
					bgColor: '',
					imageUrl: '',
					confirm: false,//删除不提示确认框
				};
				let componentsData = [];
				
				await getWebTerminal({id : params.id, posterId: params.posterId}).then(res => {
					if(res.code === 0 && res.data){
						state.editorId = res.data.id;
						state.posterId = res.data.posterId;
						terminal = res.data.terminal;
						terminalContent = JSON.parse(res.data.terminalContent);
						componentsData = JSON.parse(res.data.terminalComponent);
					}
				});
				if(!terminalContent.title){
					await getWebPoster({id : params.posterId}).then(res => {
						if(res.code === 0 && res.data){
							terminalContent.title = res.data.title; 
						}
					});
				}
				
				setTerminal(terminal);
				setTerminalContent(terminalContent ? JSON.parse(JSON.stringify(terminalContent)) : {});
				setComponentsData(componentsData ? JSON.parse(JSON.stringify(componentsData)) : []);
			}
			
			document.addEventListener('click', () => {
				setActiveComponent({});
			})
			
			document.onkeydown = (e) =>{
				let keyCode = e.keyCode;
				let activeId = state.activeComponent.id;
				//Ctrl+S
				if(e.ctrlKey && keyCode == 83){
					e.preventDefault();
					editorSave();
				}
				//Ctrl+D
				if(e.ctrlKey && keyCode == 68 && activeId){
					e.preventDefault();
					delComponent(activeId);
				}
				//Delete
				if(keyCode == 46 && activeId){
					delComponent(activeId);
				}
			}
			
			onMounted(() => {
				state.editorId = route.query.id;
				state.posterId = route.query.posterId;
				loadWebTerminal({'id': route.query.id, 'posterId': route.query.posterId});
			});

			return {
				editorPanelRef,
				scrollbarRef,
				toggleDevice,
				editorSave,
				editorClear,
				editorView,
				editorEdit,
				scrollToTop,
				switchToToolBar,
				...toRefs(state),
			};
		},
	}
</script>

<style lang="scss" scoped>
.editor-container {
	.active {
		background-color: #d9ecff;
		color: #409EFF;
	}

	.main-content-warp {
		flex: 1;
		overflow-y: auto;
		.main-editor {
			margin: 0 auto;
			max-width: 100%;
			height: calc(100vh - 220px);
		}
	}
	.main-content-gird{
		background: linear-gradient(90deg, rgba(100, 100, 100, 0.1) 5%, transparent 0), linear-gradient(rgba(100, 100, 100, 0.1) 5%, transparent 0);
		background-size: 20px 20px;
	}
	.flex-style {
		display: flex;
		align-items: center;
		height: 40px;
	
		label {
			margin-right: 15px;
		}
	
		.block {
			flex: 1;
			height: 40px;
		}
	
		:deep .el-slider__input {
			width: 50px;
		}
	
		:deep .el-slider__runway {
			height: 4px;
			margin: 18px 65px 18px 0;
		}
	
		:deep .el-slider__bar {
			height: 4px;
		}
	
		:deep .el-slider__button-wrapper {
			top: -17px;
		}
	
		:deep .el-slider__button {
			width: 12px;
			height: 12px;
		}
	
		:deep .el-input-number.is-without-controls .el-input__inner {
			padding: 10px;
		}
	}
}
</style>
